package com.libraries.image.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;

import com.libraries.base.BaseActivity;
import com.libraries.helper.Logger;
import com.libraries.image.listener.IImageLoadingListener;
import com.libraries.image.tasker.ImgLoadTasker;
import com.libraries.image.view.ClipImageLayout;
import com.libraries.view.TitleBarView;
import com.example.libraries.R;

public class ImageClipviewActivity extends BaseActivity implements OnClickListener{
	private ClipImageLayout clipLayout;
	private Bitmap bitmap;
	private String filePath;

	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_clipview);
		initClipData();
		initClipTitle();
		initClipView();
	}
	
	private void initClipData(){
		filePath=getIntent().getStringExtra("filePath");
		Logger.log(this, "initClipData", filePath);
	}
	
	private void initClipTitle() {
		TitleBarView barView = TitleBarView.getInstance();
		barView.createTitle(this,null, 0);
		barView.createLeftButton(R.string.do_cancel, null, 0).setOnClickListener(this);
		barView.createRightButton(R.string.do_clipper, null, 0).setOnClickListener(this);
	}
	
	private void initClipView(){
		clipLayout = (ClipImageLayout) findViewById(R.id.v_clipview);
		new ImgLoadTasker(new IImageLoadingListener() {
			@Override
			public void onLoadingFailed(String path, String reason, View view) {
				Logger.log("ImagerClipviewActivity", "onLoadingFailed", path,reason);
			}
			
			@Override
			public void onLoadingCompleted(String path, Bitmap bitmap,View view) {
				if (bitmap!=null) {
					ImageClipviewActivity.this.bitmap=bitmap;
					clipLayout.setBitmap(bitmap);
				}
			}
		}).execute(240,240,filePath);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_top_left) {
			doActivityResult();
		} else {
			doClipImage();
		}
	}
	
	private void doClipImage(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				Bitmap bitmap = clipLayout.clip();
				Intent intent = new Intent();
				intent.putExtra("data", bitmap);
				setResult(RESULT_OK, intent);
				finish();
			}
		}).start();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode==KeyEvent.KEYCODE_BACK) {
			doActivityResult();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void doActivityResult(){
		setResult(RESULT_CANCELED);
		finish();
	}
	
	@Override
	protected void onDestroy() {
		if (this.bitmap!=null) {
			this.bitmap.recycle();
		}
		super.onDestroy();
	}
}
